// mobile bind
// ============

define(['zepto', 'utils', 'countDown'], function($, utils){
  return {
    init: function(data) {
      this.token = null
      this.unionid=data.unionid
      this.courseId = data.courseId
      this.mobiles = data.mobiles
      utils.configWeixin(data.jsConfig, false);
      this.bindMobileBindingPageEvent();
    },

    /**
     * Bind mobile binding page event
     */
    bindMobileBindingPageEvent: function() {
      var that = this,
      $mobile = $('input[name="mobile"]'),
      $code = $('input[name="code"]');

      // On requesting verify code
      $(document).on('click', '#get-code', function(e) {
        e.preventDefault()
        
        var $button = $(e.currentTarget), mobile = $mobile.val().trim()
        if (that.isMobile(mobile)) {
          
          if (that.isStaff(mobile)) {
            // Disable button
            $button.css('pointer-events', 'none')
            // Request verifiy code
            that.requestVerifyCode(mobile, function(data) {
              
              that.token = data.token;
              $button.countdown('s后重试', 60, function() {
                $button.css('pointer-events', 'initial').text('获取验证码')
              })
            }, function() {
              $button.css('pointer-events', 'initial')
            })
          } else {
            $.toast('抱歉，非核销人员无法操作')
          }
          
        } else {
          $.toast('请输入正确的手机号码')
        }
        
      })

      // On submiting mobile
      $(document).on('click', '#submit', function(e) {
        e.preventDefault();
        
        var submitingStatus = $(this).data("submiting");
        if(submitingStatus != "true") {
          $("#submit").data("submiting", "true");
          var mobile = $mobile.val().trim(), code = $code.val().trim();
          if (!that.isMobile(mobile)) return $.toast('请输入正确的手机号码')
          if (!that.isStaff(mobile)) return $.toast('抱歉，非核销人员无法操作')
          if (!code) return $.toast('验证码不能为空')
          
          var submiting = that.submitMobile(mobile, code)
          $.when(submiting).done(function(data) {
            $("#submit").data("submiting", "false");
            if(data.redirect && data.redirect != '/') {
              window.location.href = window.__CTX__.root + data.redirect;
            } else {
              window.location.href = window.__CTX__.root + "/staffs/verificate?courseId=" + that.courseId;
            }
          })
        }
      })
    },

    /**
     * Check mobile value is valid or not
     */
    isMobile: function(mobile) {
      return mobile && /^((13)|(15)|(17)|(18))\d{9}$/.test(mobile)
    },
    
    /**
     * Check mobile_user whether staff
     */
    isStaff: function(mobile) {
      var that = this;
      return that.mobiles.indexOf(mobile) != -1 ? true : false;
    },

    /**
     * Request server to send verifiy code to mobile
     */
    requestVerifyCode: function(mobile, success, failure) {
      $.showIndicator()
      utils.requestVerifyCode(mobile, function(result) {
        $.hideIndicator()
        $.toast('验证码发送成功')
        success && success(result.data)
      }, failure)
    },

    /**
     * Submit mobile and code for binding
     */
    submitMobile: function(mobile, code) {
      var that = this, defer = $.Deferred()
      $.showIndicator()
      $.post(window.__CTX__.root + '/api/profile/auth', {'unionid': that.unionid, 'mobile': mobile, 'code': code, 'token': that.token})
        .done(function(response) {
          $.hideIndicator()
          utils.processResult(response, function(result) {
            $.toast(result.message || '绑定手机成功')
            defer.resolve(result.data)
          }, function(result) {
            $("#submit").data("submiting", "false");
            $.toast(result.message || '绑定手机失败')
          })
        })
        
      return defer.promise()
    }
    
  }

})